import {
  Body,
  Controller,
  Delete,
  Get,
  Head,
  Header,
  Headers,
  HostParam,
  HttpCode,
  HttpException,
  HttpStatus,
  Inject,
  Ip,
  Next,
  Optional,
  Options,
  Param,
  Patch,
  Post,
  Put,
  Query,
  Redirect,
  Req,
  Res,
  Session,
  SetMetadata,
  UseFilters,
  UseGuards,
  UseInterceptors,
  UsePipes,
} from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { TestFilter } from './test.filter';
import { LoginGuard } from './login.guard';
import { TimeInterceptor } from './time.interceptor';
import { ValidatePipe } from './validate.pipe';
import { AllDecoratorService } from './all-decorator.service';

@Controller({ host: 'localhost', path: 'api/all-decorator' })
@SetMetadata('roles', ['user'])
export class AllDecoratorController {
  constructor(
    @Optional() private readonly allDecoratorService: AllDecoratorService,
  ) {}

  @Optional()
  @Inject('huan')
  private huan: Record<string, any>;

  @Get()
  @UseFilters(TestFilter)
  @UseInterceptors(TimeInterceptor)
  @UseGuards(LoginGuard)
  @UsePipes(ValidatePipe)
  @SetMetadata('roles', ['admin'])
  aopDecoratorTest(@Param('aaa', ValidatePipe) aaa: number) {
    throw new HttpException('异常测试', HttpStatus.BAD_REQUEST);
    return this.allDecoratorService.findAll();
  }

  @Get('/headers')
  headersParams(
    @Headers('Accept') accept: string,
    @Headers() headers: Record<string, any>,
  ) {
    return { accept, headers };
  }

  @Get('/requestParams')
  requestParams(
    @HostParam('host') host,
    @Req() req: Request,
    @Param('aaa') aaa: number,
    @Query('bbb') bbb: number,
  ) {
    return { host: String(host), routeData: req.route };
  }

  @Get('/responseParams')
  responseParams(@Res({ passthrough: true }) res: Response) {
    return { data: '233' };
  }

  @Get('/next')
  nextTest1(@Next() next: NextFunction) {
    next();
    return 'next1';
  }

  @Get('/next')
  nextTest2() {
    return 'next2';
  }

  @Get('httpCodeParams')
  @HttpCode(233)
  httpCodeParams() {
    return 'httpCodeParams';
  }

  @Get('updateHeaderParams')
  @Header('customParams', 'hello')
  updateHeaderParams() {
    return 'hello';
  }

  @Get('redirectTest')
  @Redirect('http://juejin.cn')
  async redirectTest() {
    // 自定义返回 url
    return {
      url: 'https://www.baidu.com',
      statusCode: 302,
    };
  }

  @Get('/ip')
  ip(@Ip() ip: string) {
    return ip;
  }

  @Post('/postParams')
  postParams(@Body() aaa) {
    return { aaa };
  }

  @Put()
  putParams() {
    return 'putParams';
  }

  @Delete()
  deleteParams() {
    return 'deleteParams';
  }

  @Patch()
  patchParams() {
    return 'patchParams';
  }

  @Options()
  optionsParams() {
    return 'optionsParams';
  }

  @Head()
  headParams() {
    return 'headParams';
  }
}
